<template>
  <div class="content">
    <div class="header">
      <h3 class="title">{{ contentConfig?.header?.title ?? '数据列表' }}</h3>
      <el-button
        v-permission="`${apiPermission}:create`"
        type="primary"
        icon="Plus"
        @click="handleNewUserClick"
        >{{ contentConfig.header?.btnContent ?? '新建数据' }}</el-button
      >
    </div>
    <div class="table">
      <template v-if="isCreate || isDelete || isUpdate">
        <el-table
          :data="pageList"
          border
          style="width: 100%"
          highlight-current-row
          v-bind="contentConfig.childrenTree"
        >
          <template v-for="item in contentConfig.propItems" :key="item.prop">
            <template v-if="item.type === 'timer'">
              <el-table-column v-bind="item">
                <template #default="scope">
                  {{ formatUTC(scope.row[item.prop]) }}
                </template>
              </el-table-column>
            </template>
            <template v-else-if="item.type === 'operation'">
              <el-table-column :width="item.width" v-bind="item">
                <template #default="scope">
                  <div class="btns">
                    <el-button
                      v-permission="`${apiPermission}:update`"
                      size="small"
                      icon="Edit"
                      type="primary"
                      text
                      @click="handleEditClick(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      v-permission="`${apiPermission}:delete`"
                      size="small"
                      icon="Delete"
                      type="danger"
                      text
                      @click="handleDeleteClick(scope.row)"
                      >删除</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </template>
            <template v-else-if="item.type === 'custom'">
              <el-table-column v-bind="item">
                <template #default="scope">
                  <slot
                    :name="item.slotName"
                    v-bind="scope"
                    :prop="item.prop"
                  ></slot>
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <el-table-column v-bind="item"></el-table-column>
            </template>
          </template>
        </el-table>
      </template>
      <template v-else>
        <div>没有权限或数据！</div>
      </template>
    </div>
    <div
      class="pagination"
      v-if="
        !contentConfig.isHidePagination && (isCreate || isUpdate || isDelete)
      "
    >
      <el-pagination
        :total="pageTotalCount || 1"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30]"
        size="default"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
// 模块引入
import { ref, toRaw } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessageBox, ElNotification } from 'element-plus'

import type { IContentProps } from '@/components/types'
import { formatUTC } from '@/utils/timeFormat'
import { usePermissions } from '@/components/hooks'

import useSystemStore from '@/store/main/system/system'
import useLoginStore from '@/store/login'
// 组件配置
defineOptions({
  // 组件名称
  name: 'PageContent',
  // 继承透传，是否继承没在子组件声明的父组件的属性
  inheritAttrs: true
})

// 1、接收父组件传递的属性
const props = defineProps<IContentProps>()
const emit = defineEmits(['newClick', 'editClick'])

// 2、获取当前分类的名称
const { category, pageName } = props.contentConfig
const apiPageName = `${category}/${pageName}`
const apiPermission = `${category}:${pageName}`
// console.log(category, pageName)

// 3、获取当前分类的store
const systemStore = useSystemStore()
const { pageList, pageTotalCount } = storeToRefs(systemStore)

const loginStore = useLoginStore()
const currentPage = ref(1)
const pageSize = ref(10)
/** 分页器回显，利用pinia */
systemStore.$onAction(({ name, after }) => {
  // 在action执行完毕后执行
  after(() => {
    // 如果action的名称是createPageAction、deletePageByIdAction或updatePageAction
    if (
      name === 'createPageAction' ||
      name === 'deletePageByIdAction' ||
      name === 'updatePageAction'
    ) {
      // 将currentPage的值设置为1
      currentPage.value = 1
      // 调用loginStore中的loadLocalCacheAction方法,
      loginStore.loadLocalCacheAction()
    }
  })
})

const isCreate = usePermissions(`${category}:${pageName}:create`)
const isDelete = usePermissions(`${category}:${pageName}:delete`)
const isUpdate = usePermissions(`${category}:${pageName}:update`)
const isQuery = usePermissions(`${category}:${pageName}:query`)

const handleNewUserClick = () => {
  emit('newClick')
}

const handleEditClick = (row: any) => {
  emit('editClick', row)
}

const handleDeleteClick = (row: any) => {
  const cn = {
    user: '用户',
    role: '角色',
    menu: '菜单',
    department: '部门'
  }
  const pageNameCn = cn[pageName as keyof typeof cn] ?? pageName
  const { _id: id, name = '', username = '' } = { ...row }
  ElMessageBox.confirm(
    `确认删除名称为：${name ?? username}的该数据吗？`,
    `${pageNameCn}页面删除提示`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      systemStore.deletePageByIdAction(apiPageName, id)
      ElNotification.success({ message: `${name ?? username}数据已成功删除` })
    })
    .catch(() => {
      ElNotification.info({ message: '已取消删除' })
    })
}

fetchPageListData()

function handleSizeChange() {
  fetchPageListData()
}

function handleCurrentChange() {
  fetchPageListData()
}

function fetchPageListData(queryInfo: any = {}) {
  if (!isQuery) return
  // 1、收集分页参数数据
  const limit = pageSize.value
  const page = currentPage.value
  const info = { limit, page }
  // 2、将查询参数拼接到info中
  const partquery = toRaw(queryInfo)
  const query = Object.assign({}, info, partquery || {})
  // console.log(query)
  // 3、发起网络请求
  systemStore.postListAction(apiPageName, query)
}

defineExpose({
  fetchPageListData
})
</script>

<style scoped lang="scss">
.content {
  margin-top: 20px;
  background: #fff;
  padding-top: 20px;
  .header {
    padding: 0 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  .btns {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .pagination {
    display: flex;
    justify-content: flex-end;
    padding: 20px;
  }
}
</style>
